package com.learn.config;

import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.*;

/**
 * @author suyafei
 */
public class XMLMapperBuilder {
    /**
     * crudType:
     *  1.select
     *  2.insert
     *  3.update
     *  4.delete
     */
    private final List<String> CRUD_NODE = Arrays.asList("//select", "//insert","//update", "//delete");
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //解析crud标签
        List<Map<String,List<Element>>> crudElementList = new ArrayList<>();
        for (String curd : CRUD_NODE) {
            List<Element> curdList = rootElement.selectNodes(curd);
            Map<String, List<Element>> crudMap = new HashMap<>();
            crudMap.put(curd, curdList);
            crudElementList.add(crudMap);
        }

        for (Map<String, List<Element>> crudMap : crudElementList) {
            Object[] keys = crudMap.keySet().toArray();
            for (int i = 0; i < keys.length; i++) {
                String keyType = keys[i].toString();
                List<Element> elements = crudMap.get(keyType);
                for (Element element : elements) {
                    String id = element.attributeValue("id");
                    String resultType = element.attributeValue("resultType");
                    String parameterType = element.attributeValue("parameterType");
                    String sqlText = element.getTextTrim();

                    MappedStatement mappedStatement = new MappedStatement();
                    mappedStatement.setId(id);
                    mappedStatement.setParameterType(parameterType);
                    mappedStatement.setResultType(resultType);
                    mappedStatement.setSql(sqlText);
                    mappedStatement.setCrudType(keyType);

                    String key = namespace + "." + id;
                    configuration.getMappedStatementMap().put(key, mappedStatement);
                }
            }
        }
    }
}


